package org.openmore.opc.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.openmore.common.CommonUtils;
import org.openmore.common.date.DateUtil;
import org.openmore.common.enums.Platform;
import org.openmore.common.excel.ExportExcelUtils;
import org.openmore.common.exception.OpenmoreException;
import org.openmore.common.redis.RedisOps;
import org.openmore.common.str.UserAgentUtils;
import org.openmore.opc.dao.UserMapper;
import org.openmore.opc.dto.UserProfileDto;
import org.openmore.opc.dto.api.DictionaryDto;
import org.openmore.opc.dto.api.UserDto;
import org.openmore.opc.entity.User;
import org.openmore.opc.entity.enums.LoginType;
import org.openmore.opc.entity.enums.UserType;
import org.openmore.opc.framework.MyThreadLocalConfig;
import org.openmore.opc.framework.ReferencedFieldProcessor;
import org.openmore.opc.service.DictionaryService;
import org.openmore.opc.service.UserService;
import org.openmore.opc.utils.ShiroMd5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class UserServiceImpl extends BaseServiceImpl implements UserService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private ReferencedFieldProcessor processor;

    @Autowired
    private RedisOps redisOps;


    private UserDto convert(User user) {
        if (null == user) {
            return null;
        }
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);
        processor.processOne(userDto);
        return userDto;
    }

    private List<UserDto> convert(List<User> users) {
        if (CollectionUtils.isEmpty(users)) {
            List<UserDto> userDto = new ArrayList<>();
            return userDto;
        }
        List<UserDto> userDtos = new ArrayList<>();
        for (User user : users) {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(user, userDto);
            processor.processOne(userDto);
            /*Integer playCount = watchRecordService.selectCount(userDto.getId());
            Integer favouriteCount = userFavoriteService.selectCount(userDto.getId(), null);
            Integer buyCount = commonOrderService.selectCount(userDto.getId(), null, null, null, null,
                    null, OrderForeignType.VIDEO,null, null);
            userDto.setPlayCount(playCount);
            userDto.setFavouriteCount(favouriteCount);
            userDto.setBuyCount(buyCount);*/
            userDtos.add(userDto);
        }
        return userDtos;
    }

    /**
     * 根据id获得实体对象
     *
     * @param id
     */
    @Override
    public User getEntityById(String id) {
        if(StringUtils.isEmpty(id)){
            return null;
        }
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("id", id).andEqualTo("deleted", false);
        return userMapper.selectOneByExample(example);
    }

    /**
     * 根据id获得DTO对象
     *
     * @param id
     */
    @Override
    public UserDto getDtoById(String id) {
        return convert(getEntityById(id));
    }

    @Override
    public User getByOpenid(LoginType type, String openid) {
        if(null == type || StringUtils.isEmpty(openid)){
            return null;
        }
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria().andEqualTo("deleted", false);
        if(type == LoginType.WECHAT_OPEN){
            criteria.andEqualTo("wechatOpenid", openid);
        }else if(type == LoginType.WECHAT_MINIAPP){
            criteria.andEqualTo("miniAppOpenid", openid);
        }
        else if(type == LoginType.QQ){
            criteria.andEqualTo("qqOpenid", openid);
        }
        User user = userMapper.selectOneByExample(example);
        return user;
    }

    /**
     * 获得员工类型列表
     *
     * @return
     */
    @Override
    public List<DictionaryDto> getUserTypeList() {
        List<DictionaryDto> typeList = new ArrayList<>();
        DictionaryDto dto = dictionaryService.getDtoById("");
        typeList.add(dto);
        dto = dictionaryService.getDtoById("User");
        typeList.add(dto);
        return typeList;
    }

    /**
     * 获得所有记录
     *
     * @return
     */
    @Override
    public List<UserDto> selectAll(String tenantId, String username, UserType type, String roleId, Boolean isVip, String phone, Platform platform, Date startTime, Date endTime) {
        String platName = platform == null ? null : platform.getDisplayName();
        return convert(userMapper.selectUsers(tenantId, username, type, roleId, isVip, phone, platName, startTime, endTime));
    }

    /**
     * 获得所有数量
     *
     * @return
     */
    @Override
    public long selectAllCount(String tenantId, String username, UserType type, String roleId, Boolean isVip, String phone, Platform platform, Date startTime, Date endTime) {
        String platName = platform == null ? null : platform.getValue();
        Long count = userMapper.selectUserCount(tenantId, username, type, roleId, isVip, phone, platName, startTime, endTime);
        return null == count ? 0 : count;
    }


    public UserDto insert(UserDto dto) {
        User entity = new User();
        BeanUtils.copyProperties(dto, entity);
        return this.insert(entity);
    }

    /**
     * 带UUID的插入
     * 所有的插入数据，都要调用这个实现
     *
     * @param entity
     */
    @Override
    @Transactional
    public UserDto insert(User entity) {
        if(null == entity){
            throw new OpenmoreException(400, "参数不能为空");
        }
        if(StringUtils.isEmpty(entity.getTenantId())){
            throw new OpenmoreException(400, "账户所属应用不能为空");
        }
        // 密码不能为空
        // 三方登录信息不能全为空
        // 手机号和邮件不能全为空
        /*if (StringUtils.isEmpty(entity.getEmail()) && StringUtils.isBlank(entity.getPhone()) ||
                (StringUtils.isBlank(entity.getQqOpenid()) && StringUtils.isBlank(entity.getWechatOpenid()) && StringUtils.isBlank(entity.getWeiboOpenid()))) {
            throw new InvalidParamsException("缺少必须的参数，请检查三方登录信息/邮箱/手机号/密码");
        }*/

        Example example = new Example(User.class);
        // 判断邮件是否存在
        if (!StringUtils.isBlank(entity.getEmail())) {
            example.createCriteria().andEqualTo("tenantId").andEqualTo("email", entity.getEmail()).andEqualTo("deleted", false);
            if (!CollectionUtils.isEmpty(userMapper.selectByExample(example))) {
                throw new OpenmoreException("账号：【" + entity.getEmail() + "】已经存在");
            }
        }
        // 判断手机是否存在
        if (!StringUtils.isBlank(entity.getPhone())) {
            example = new Example(User.class);
            example.createCriteria().andEqualTo("tenantId").andEqualTo("phone", entity.getPhone()).andEqualTo("deleted", false);
            if (!CollectionUtils.isEmpty(userMapper.selectByExample(example))) {
                throw new OpenmoreException("手机号：【" + entity.getPhone() + "】已经存在");
            }
        }
        // 判断三方信息是否存在
        if (!StringUtils.isEmpty(entity.getWechatOpenid())){
            example = new Example(User.class);
            example.createCriteria().andEqualTo("wechatOpenid", entity.getWechatOpenid()).andEqualTo("deleted", false);
            if (!CollectionUtils.isEmpty(userMapper.selectByExample(example))) {
                throw new OpenmoreException("微信用户：【" + entity.getNickname() + "】已经存在");
            }
        }
        // 判断三方信息是否存在
        if (!StringUtils.isEmpty(entity.getMiniAppOpenid())){
            example = new Example(User.class);
            example.createCriteria().andEqualTo("miniAppOpenid", entity.getMiniAppOpenid()).andEqualTo("deleted", false);
            if (!CollectionUtils.isEmpty(userMapper.selectByExample(example))) {
                throw new OpenmoreException("小程序用户：【" + entity.getNickname() + "】已经存在");
            }
        }
        // 判断三方信息是否存在
        if (!StringUtils.isEmpty(entity.getWeiboOpenid())){
            example = new Example(User.class);
            example.createCriteria().andEqualTo("weiboOpenid", entity.getWeiboOpenid()).andEqualTo("deleted", false);
            if (!CollectionUtils.isEmpty(userMapper.selectByExample(example))) {
                throw new OpenmoreException("微博用户：【" + entity.getNickname() + "】已经存在");
            }
        }
        // 判断三方信息是否存在
        if (!StringUtils.isEmpty(entity.getQqOpenid())){
            example = new Example(User.class);
            example.createCriteria().andEqualTo("qqOpenid", entity.getQqOpenid()).andEqualTo("deleted", false);
            if (!CollectionUtils.isEmpty(userMapper.selectByExample(example))) {
                throw new OpenmoreException("QQ用户：【" + entity.getNickname() + "】已经存在");
            }
        }
        /**判断用户来源*/
        Platform platform = UserAgentUtils.parseFromUserAgent(MyThreadLocalConfig.getUserAgent(), MyThreadLocalConfig.getScope());
        if (null != entity && null == entity.getRegistFrom() && null != platform) {
            entity.setRegistFrom(platform);
        }
        if(null==entity.getIsVip()){
            entity.setIsVip(false);
        }
        if(null == entity.getLocked()){
            entity.setLocked(false);
        }
        if(null == entity.getUserType()){
            entity.setUserType(UserType.USER);
        }
        if(null==entity.getForbiddenWords()){
            entity.setForbiddenWords(false);
        }
        beforeInsert(entity);
        entity.setSalt(CommonUtils.getUUID());
        if (!StringUtils.isBlank(entity.getPassword())) {
            entity.setPassword(generatePassword(entity.getSalt(), entity.getPassword()));
        }
        userMapper.insert(entity);
        insertLog("添加用户：" + entity.getNickname());

        return this.getDtoById(entity.getId());
    }

    /**
     * 删除指定id的数据
     */
    @Override
    public void deleteById(String id) {
        User entity = this.getEntityById(id);
        if (entity != null) {
            Example example = new Example(User.class);
            example.createCriteria().andEqualTo("id", id).andEqualTo("deleted", false);
            entity.setDeleted(true);
            userMapper.updateByExampleSelective(entity, example);
            insertLog("delete User");
        }
    }

    @Override
    public void update(UserDto dto) {
        User entity = new User();
        BeanUtils.copyProperties(dto, entity);
        this.update(entity);
    }

    /**
     * 修改数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User entity) {
        if (StringUtils.isEmpty(entity.getId())) {
            throw new OpenmoreException("id不能为空");
        }
        User old = getEntityById(entity.getId());
        if (null == old) {
            throw new OpenmoreException("id非法");
        }
        Example example = new Example(User.class);
        if (!StringUtils.isEmpty(entity.getEmail()) && !old.getEmail().equals(entity.getEmail())) {
            example.createCriteria().andEqualTo("email", entity.getEmail()).andEqualTo("deleted", false);
            List<User> Users = userMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(Users)) {
                throw new OpenmoreException("当前登录邮箱：【" + entity.getEmail() + "】已经存在");
            }
        }
        if (!StringUtils.isEmpty(entity.getPhone()) && !old.getPhone().equals(entity.getPhone())) {
            example = new Example(User.class);
            example.createCriteria().andEqualTo("phone", entity.getPhone()).andEqualTo("deleted", false);
            List<User> Users = userMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(Users)) {
                throw new OpenmoreException("当前手机号：【" + entity.getPhone() + "】已经存在");
            }
        }
        beforeUpdate(entity);
        example = new Example(User.class);
        example.createCriteria().andEqualTo("id", entity.getId());
        userMapper.updateByExampleSelective(entity, example);
        insertLog("更新用户信息：" + entity.getNickname());
        User User = getEntityById(entity.getId());
//      更新用户信息后，需要更新session里的用户信息
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute(subject.getPrincipal(), JSON.toJSONString(User));
        // 清除process缓存
        processor.flushCache(User.class);
    }

    /**不需要更新缓存的修改*/
    @Override
    @Transactional
    public void updateNoCache(User entity){
        if (StringUtils.isEmpty(entity.getId())) {
            throw new OpenmoreException("id不能为空");
        }
        User old = getEntityById(entity.getId());
        if (null == old) {
            throw new OpenmoreException("id非法");
        }
        Example example = new Example(User.class);
        if (!StringUtils.isEmpty(entity.getEmail()) && !old.getEmail().equals(entity.getEmail())) {
            example.createCriteria().andEqualTo("email", entity.getEmail()).andEqualTo("deleted", false);
            List<User> Users = userMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(Users)) {
                throw new OpenmoreException("当前登录邮箱：【" + entity.getEmail() + "】已经存在");
            }
        }
        if (!StringUtils.isEmpty(entity.getPhone()) && !old.getPhone().equals(entity.getPhone())) {
            example = new Example(User.class);
            example.createCriteria().andEqualTo("phone", entity.getPhone()).andEqualTo("deleted", false);
            List<User> Users = userMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(Users)) {
                throw new OpenmoreException("当前手机号：【" + entity.getPhone() + "】已经存在");
            }
        }
        beforeUpdate(entity);
        example = new Example(User.class);
        example.createCriteria().andEqualTo("id", entity.getId());
        userMapper.updateByExampleSelective(entity, example);
        insertLog("更新用户信息：" + entity.getNickname());
    }

    /**
     * 根据用户名，获得User对象
     *
     * @param email
     * @return
     */

    @Override
    public User getUserByEmail(String tenantId, String email) {
        if(StringUtils.isEmpty(tenantId)){
            throw new OpenmoreException(400, "应用ID不能为空");
        }
        if(StringUtils.isEmpty(tenantId)){
            throw new OpenmoreException(400, "邮箱不能为空");
        }
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("tenantId").andEqualTo("email", email).andEqualTo("deleted", false);
        return userMapper.selectOneByExample(example);
    }

    @Override
    public User getUserByPhone(String tenantId, String phone) {
        if(StringUtils.isEmpty(tenantId)){
            throw new OpenmoreException(400, "应用ID不能为空");
        }
        if(StringUtils.isEmpty(phone)){
            throw new OpenmoreException(400, "手机号码不能为空");
        }
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("tenantId").andEqualTo("phone", phone).andEqualTo("deleted", false);
        List<User> users = userMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(users)) {
            return users.get(0);
        }
        return null;
    }

    /**
     * 验证User里的密码和pwd是否一致
     * 会使用salt进行加密
     *
     * @param User
     * @param pwd
     * @return
     */
    @Override
    public boolean validatePassword(User User, String pwd) {
        return User.getPassword().equals(ShiroMd5Utils.md5(pwd, User.getSalt()));
    }

    /**
     * 生成newPassword的密码
     * 会使用User.salt进行加密
     *
     * @param salt
     * @return
     */
    @Override
    public String generatePassword(String salt, String newPassword) {
        return ShiroMd5Utils.md5(newPassword, salt);
    }

    /**
     * 修改密码
     */
    @Override
    public void changePassword(User user, String newPassword) {
        User entity = this.getEntityById(user.getId());
        entity.setPassword(this.generatePassword(entity.getSalt(), newPassword));
        this.update(entity);
    }
    /**
     * 设置初始登录密码
     * , String repeatPassword
     */
    @Override
    public void setPassword(User user, String password) {
        if(null == user || StringUtils.isEmpty(user.getId())){
            throw new OpenmoreException(400, "请先登录");
        }
        /*if(StringUtils.isEmpty(password) || StringUtils.isEmpty(repeatPassword)){
            throw new OpenmoreException(400, "请填写密码");
        }
        if(!password.equals(repeatPassword)){
            throw new OpenmoreException(400, "两次密码不一致");
        }*/
        User entity = this.getEntityById(user.getId());
        if(!StringUtils.isEmpty(entity.getPassword())){
            throw new OpenmoreException(400, "您已经设置过密码");
        }
        entity.setPassword(this.generatePassword(entity.getSalt(), password));
        this.update(entity);
    }

    /**
     * 返回拥有指定权限的员工列表
     *
     * @param permissionCode
     * @return
     */
    public List<UserDto> selectHasPermissionUserList(String permissionCode) {
        return userMapper.selectHasPermissionUser(permissionCode);
    }

    /**
     * 获取数据看板用户统计
     */
    @Override
    public Map<String, Long> getDataDashBoard(String tenantId) {
        Map<String, Long> result = new HashMap<>();
        long totalUser = selectAllCount(tenantId, null, null, null, null, null,
                null, null, null);
        long userFromAndroid = selectAllCount(tenantId, null, null, null, null, null,
                Platform.ANDROID, null, null);
        long userFromAndroidPad = selectAllCount(tenantId, null, null, null, null, null,
                Platform.ANDROIDPAD, null, null);
        long userFromIphone = selectAllCount(tenantId, null, null, null, null, null,
                Platform.IPHONE, null, null);
        long userFromIpad = selectAllCount(tenantId, null, null, null, null, null,
                Platform.IPAD, null, null);
        long userFromMiniapp = selectAllCount( tenantId, null, null, null, null, null,
                Platform.MINIAPP, null, null);
        long userFromOthers = selectAllCount(tenantId, null, null, null, null, null,
                Platform.OTHERS, null, null);
        result.put("totalUser", totalUser);
        result.put("userFromAndroid", userFromAndroid);
        result.put("userFromIphone", userFromIphone);
        result.put("userFromAndroidPad", userFromAndroidPad);
        result.put("userFromIpad", userFromIpad);
        result.put("userFromMiniapp", userFromMiniapp);
        result.put("userFromOthers", userFromOthers);
        return result;
    }

    /**
     * 获取数据看板用户折线图
     */
    @Override
    public List<Map<String, Long>> getTotalUserDataDashBoard(String tenantId) {
        List<Map<String, Long>> result = new ArrayList<>();
        Date firstDate = DateUtil.getMonthFirstDay(new Date(), true);
        Long firstCount = selectAllCount(tenantId, null, null, null, null, null,
                null, firstDate, new Date());
        Map<String, Long> firstMap = new HashMap<>();
        firstMap.put(DateUtil.dateToString(DateUtil.DATE_MONTH_PATTERN, firstDate), firstCount);
        result.add(firstMap);
        Date endTime = firstDate;
        for (int i = 0; i < 11; i++) {
            Date startDate = DateUtil.getMonthFirstDay(new Date(endTime.getTime() - 1000), true);
            Long resultCount = selectAllCount(tenantId, null, null, null, null, null,
                    null, startDate, endTime);
            Map<String, Long> resultMap = new HashMap<>();
            resultMap.put(DateUtil.dateToString(DateUtil.DATE_MONTH_PATTERN, startDate), resultCount);
            result.add(resultMap);
            endTime = startDate;
        }
        Collections.reverse(result);
        return result;
    }

    /**
     * 导出用户列表表格
     */
    @Override
    public void expertUserExcel(HttpServletResponse response, List<UserDto> userDtos) {
        if (CollectionUtils.isEmpty(userDtos)) {
            throw new OpenmoreException("没有数据");
        }

        // 创建excel：1、组装表头，2、组装行，3、设置文件名和表标题
        List<List<Object>> rows = new ArrayList();
        int i = 0;
        for (UserDto userDto : userDtos) {
            i++;
            List<Object> row = new ArrayList<Object>();
            row.add(i);
            row.add(userDto.getPhone());
            row.add(DateUtil.dateToString(DateUtil.FULL_TIME_PATTERN, userDto.getUpdatedTime()));
            row.add(DateUtil.dateToString(DateUtil.FULL_TIME_PATTERN, userDto.getCreatedTime()));
            rows.add(row);
        }
        try {
            String[] titleTexts = {"序号", "客户名", "手机号", "客户公司", "咨询次数", "TA的心愿单", "上次登录时间", "创建时间"};
            List<String> titles = CollectionUtils.arrayToList(titleTexts);
            String fileName = CommonUtils.getNowDateHumanReadString(4);
            ExportExcelUtils.httpFastCreate(response, fileName + ".xlsx", "客户", titles, rows);
        } catch (Exception e) {
            logger.error("expertUserExcel error:" + e.getMessage());
            throw new OpenmoreException("创建文件失败");
        }
    }

    /**换绑手机号*/
    @Override
    public void changePhone(String userId, String phone, String captcha){
        if(StringUtils.isEmpty(userId)){
            throw new OpenmoreException(400, "用户ID不能为空");
        }
        if(StringUtils.isEmpty(phone)){
            throw new OpenmoreException(400, "手机号码不能为空");
        }
        if(StringUtils.isEmpty(captcha)){
            throw new OpenmoreException(400, "验证码不能为空");
        }
        User old = getEntityById(userId);
        String saveCode = redisOps.get(phone);
        if (saveCode == null) {
            throw new OpenmoreException("验证码已超时，请重新发送");
        }
        if (!saveCode.equals(captcha)) {
            throw new OpenmoreException(400, "验证码错误");
        }
        User user = getUserByPhone(old.getTenantId(), CommonUtils.trimPhonePrefixCode(phone));
        if(null != user){
            throw new OpenmoreException(400, "该手机号码已被使用");
        }
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("deleted", false).andEqualTo("id", userId);
        User user1 = new User();
        user1.setPhone(phone);
        userMapper.updateByExampleSelective(user1, example);
        user1 = getUserByPhone(old.getTenantId(), CommonUtils.trimPhonePrefixCode(phone));
        if(null == user1){
            throw new OpenmoreException(400,"绑定失败");
        }
        //删除旧的缓存
        //SecurityUtils.getSubject().getSession().removeAttribute(old.getPhone());
        //更新缓存
        SecurityUtils.getSubject().getSession().setAttribute(phone, JSON.toJSONString(user1));
        MyThreadLocalConfig.setUser(user1);
    }

    /**换绑定微信号*/
    @Transactional
    @Override
    public UserProfileDto userBindWechat(String userId, String openId, String nickName){
        if(StringUtils.isEmpty(userId)){
            throw new OpenmoreException(400, "请先登录");
        }
        if(StringUtils.isEmpty(openId)){
            throw new OpenmoreException(400, "参数openID不能为空");
        }
        if(StringUtils.isEmpty(nickName)){
            throw new OpenmoreException(400, "微信昵称不能为空");
        }
        User user = getEntityById(userId);
        if(null == user){
            throw new OpenmoreException(400, "用户ID非法");
        }
        User user2 = getByOpenid(LoginType.WECHAT_OPEN, openId);
        if(null!=user2 && !StringUtils.isEmpty(user2.getPhone())){
            throw new OpenmoreException(400, "此微信号已被绑定");
        }
        user.setWechatOpenid(openId);
        user.setWechatName(nickName);
        update(user);
        UserProfileDto profile = new UserProfileDto();
        profile.setId(user.getId());
//        profile.setWbOpenId(user.get);
        profile.setAvatarUrl(user.getAvatarUrl());
        profile.setCreatedTime(user.getCreatedTime());
        profile.setUpdatedTime(user.getUpdatedTime());
        profile.setLocation(user.getLocation());
        profile.setBirthday(user.getBirthday());
//        profile.setUsername(user.getNickname());
        profile.setGender(user.getGender());
        profile.setUsername(user.getNickname());
        profile.setType(user.getUserType());
        profile.setMiniAppOpenId(user.getMiniAppOpenid());
        profile.setWxOpenId(user.getWechatOpenid());
        profile.setQqOpenId(user.getQqOpenid());
        profile.setWechatName(user.getWechatName());
//        if (residentDto != null) {
//            profile.setId(residentDto.getId());
//            profile.setBirthday(residentDto.getBirthday());
//            profile.setGender(residentDto.getGender());
//            profile.setType("RESIDENT");
//            profile.setUsername(residentDto.getName());
//            profile.setFullAddress(residentDto.getFullAddress());
//            profile.setLocation(residentDto.getFullAddress());
//            profile.setIdno(CommonUtils.replaceIdNumber(residentDto.getIdno()));
//        }
        //insertLog("用户微信登录：" + token.getUsername());
        if(SecurityUtils.getSubject().isAuthenticated()){
            Session session = SecurityUtils.getSubject().getSession();
            profile.setToken((String) session.getId());
            profile.setPhone(CommonUtils.replacePhoneNumber(user.getPhone()));
        }else{
            profile.setPhone(user.getPhone());
        }
        return profile;
    }
}
